package main

import (
	"bytes"
	"flag"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
	"time"

	jsoniter "github.com/json-iterator/go"
)

type MESSAGES struct {
	Touser  string `json:"touser"`
	Toparty string `json:"toparty"`
	Msgtype string `json:"msgtype"`
	Agentid int    `json:"agentid"`
	Text    struct {
		//Subject string `json:"subject"`
		Content string `json:"content"`
	} `json:"text"`
	Safe int `json:"safe"`
}
type JSON struct {
	Access_token string `json:"access_token"`
}

var jsonwechat = jsoniter.ConfigCompatibleWithStandardLibrary

// GetAccessToken 获取token
func GetAccessToken(corpid, corpsecret string) string {
	// gettokenUrl := "https://qyapi.weixin.qq.com:1443/cgi-bin/gettoken?corpid=" + corpid + "&corpsecret=" + corpsecret
	// gettokenUrl := "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpid + "&corpsecret=" + corpsecret
	flag.Parse()
	//fmt.Println("Qywechat: ", *Qywechat)
	// gettokenUrl 企业微信 URL

	gettokenUrl := *Qywechat + "/cgi-bin/gettoken?corpid=" + corpid + "&corpsecret=" + corpsecret
	//print(gettokenUrl)
	client := &http.Client{}
	req, _ := client.Get(gettokenUrl)
	defer req.Body.Close()
	body, _ := ioutil.ReadAll(req.Body)
	//fmt.Printf("\n%q",string(body))
	var jsonStr JSON
	jsonwechat.Unmarshal([]byte(body), &jsonStr)
	if *debugMode {
		fmt.Printf(time.Now().Format("2006-01-02 15:04:05"), "[debug]GETTOKEN:%q\n", jsonStr.Access_token)
	}

	return jsonStr.Access_token
}

// SendMessage 发送微信消息
func SendMessage(access_token, msg string) {
	//sendUrl := "https://qyapi.weixin.qq.com:1443/cgi-bin/message/send?access_token=" + access_token
	//sendUrl := "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + access_token
	flag.Parse()
	//fmt.Println("Qywechat: ", *Qywechat)
	sendUrl := *Qywechat + "/cgi-bin/message/send?access_token=" + access_token
	//print(sendUrl)
	client := &http.Client{}
	req, _ := http.NewRequest("POST", sendUrl, bytes.NewBuffer([]byte(msg)))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("charset", "UTF-8")
	resp, err := client.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
	//fmt.Println("response Status:", resp.Status)
	//body, _ := ioutil.ReadAll(resp.Body)
	//fmt.Println("response Body:", string(body))
	if *debugMode {
		fmt.Println(time.Now().Format("2006-01-02 15:04:05"), "[DEBUG]sendUrl:", sendUrl)
		fmt.Println(time.Now().Format("2006-01-02 15:04:05"), "[DEBUG]response Status:", resp.Status)
		body, _ := ioutil.ReadAll(resp.Body)
		fmt.Println(time.Now().Format("2006-01-02 15:04:05"), "[DEBUG]response Body:", string(body))
	}
}

func messages(touser string, toparty string, agentid int, content string) string {
	msg := MESSAGES{
		Touser:  touser,
		Toparty: toparty,
		Msgtype: "text",
		Agentid: agentid,
		Safe:    0,
		Text: struct {
			//Subject string `json:"subject"`
			Content string `json:"content"`
		}{Content: content},
	}
	sedMsg, _ := jsonwechat.Marshal(msg)
	//fmt.Printf("%s",string(sedMsg))
	if *debugMode {
		fmt.Printf(time.Now().Format("2006-01-02 15:04:05"), "%s", string(sedMsg))
	}
	return string(sedMsg)
}

// Wechat 发送微信，用于本包中其他使用方调用
func Wechat(agentid int, corpid, toparty, corpsecret, Mess string) {
	if corpid != "" {

		//fmt.Printf("[INFO]发送到微信\n")
		touser := "tanqr" //企业号中的用户帐号，在zabbix用户Media中配置，如果配置不正常，将按部门发送。
		//    agentid := 1000014    //企业号中的应用id。
		accessToken := GetAccessToken(corpid, corpsecret)
		//content := os.Args[1]
		content := Mess

		msg := strings.Replace(messages(touser, toparty, agentid, content), "\\\\", "\\", -1)
		//fmt.Println(strings.Replace(msg, "\\\\", "\\", -1))
		SendMessage(accessToken, msg)
	}
}
